/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Supplier.java
 *
 * Created on Nov 4, 2010, 10:13:29 PM
 */

package lmclogistics;

import components.Image;
import components.NButton;
import components.Text;
import components.TextArea;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import sql.Sql;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sonia Tan
 */
public class Supplier extends javax.swing.JPanel {

    /** Creates new form Supplier */
    private Image bg;
    private static JTable supplierTable;
    private JScrollPane scroll;
    public DefaultTableModel model;
    private TableColumn column;
    private NButton add;
    private NButton edit;
    private NButton delete;
    private NButton print;
    private TextArea filterField;
    private int selectedID;

    public Supplier() {
        initComponents();
        setOpaque(false);
        setLocation(getCenterX(761), getCenterY(460));
        setSize(761, 460);
        setVisible(true);
        setBg();
        supplierTable();
        initButtons();
        initFilter();
        showTable();

//        initText();
//        initFlds();
    }

    public final void setBg(){
        bg = new Image("panelb.png",761,460);

        add(bg,-1);

    }

    public int getCenterX(int x){

        int a = 919/2 - x/2;


        return a;
    }

    public int getCenterY(int x){

        int a = 577/2 - x/2;


        return a;
    }

    public void supplierTable(){
                supplierTable = new JTable(model);
		supplierTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		supplierTable.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		supplierTable.getTableHeader().setFont(new Font("Lucida Grande", Font.PLAIN, 12));
		scroll = new JScrollPane(supplierTable);
		scroll.setBounds(20,15,530,310);
		add(scroll,0);
    }

    public static void showTable(){
        try {
            String query = "SELECT * FROM Supplier WHERE deleted=0";

            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            DefaultTableModel model = new DefaultTableModel(){
			    public boolean isCellEditable(int row, int column) {
			    	return false;
				}
			};
            model.addColumn("Code");
            model.addColumn("Name");
            model.addColumn("Terms");
            model.addColumn("Beginning Balance");
            model.addColumn("Address");
            model.addColumn("Contact Person");
            model.addColumn("Telephone No.");
            model.addColumn("Fax No.");

            while(rs.next()) {
               Vector rowData = new Vector () ;

               rowData.add(rs.getString("suppCode"));
               rowData.add(rs.getString("suppName"));
               rowData.add(rs.getString("suppTerms"));
               rowData.add(rs.getString("suppBegBal"));
               rowData.add(rs.getString("suppAddr"));
               rowData.add(rs.getString("suppConPerson"));
               rowData.add(rs.getString("suppTelNo"));
               rowData.add(rs.getString("suppFaxNo"));
               model.addRow(rowData);
            }

            supplierTable.setModel(model);

            Sql.closeSqlConnection(connection);

        } catch (Exception ex) {
            Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void initButtons(){

        edit = new NButton("Edit", 560, 15);
        edit.setSize(180,25);
        add(edit,0);

        add = new NButton("Add", 560, 40);
        add.setSize(180,25);
        add(add,0);

        delete = new NButton("Delete", 560, 65);
        delete.setSize(180,25);
        add(delete,0);

        print = new NButton("Print", 560, 300);
        print.setSize(180,25);
        add(print,0);

        if(Main.login.getAType() == 1 || Main.login.getAType() == 2)
                    delete.setEnabled(false);

        buttonlisteners();
    }


    public void initFilter(){
        Text filter = new Text();

        filter.inText("Filter:", 20, 360);
        add(filter,0);
        filterField = new TextArea();
        filterField.initText(200, 25,70, 358);
        filterField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {                
                filterTable();
            }
        });
        add(filterField,0);

    }

    public String getData(JTable table, int row_index, int col_index){
        return table.getModel().getValueAt(row_index, col_index).toString();
    }

    public void buttonlisteners()
    {
        edit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
               EditSupplier es;
               if (supplierTable.getSelectedRow() != -1)
               {
                   selectedID = Integer.parseInt(getData(supplierTable, supplierTable.getSelectedRow(), 0));
                   es = new EditSupplier(selectedID);
               }
               else
               {
                   SelectRow sr = new SelectRow("edit");
               }
            }
        });

        add.addActionListener((ActionListener) new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                AddSupplier ac = new AddSupplier();
            }
        });

        delete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                ConfirmDelete del;
                if (supplierTable.getSelectedRow() != -1){
                    del = new ConfirmDelete(4,getData(supplierTable,supplierTable.getSelectedRow(),0));
                }
                else
                {
                    SelectRow sr = new SelectRow("delete");
                }
            }
        });

        print.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae)
            {
                try {
                    supplierTable.print();
                } catch(Exception e)
                {

                }
            }
        });
    }

    public static void delData(String code){
         try {
            String query = "UPDATE supplier SET deleted= 1 WHERE suppCode="+code;

            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(query);

        }   catch (Exception ex) {
            Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void filterTable(){

        String key = filterField.getText()+"%";

        if(key.contains("dele") || key.contains("delet") || key.contains("delet") || key.contains("delete") || key.equals("deleted"))
        {
            try {
                String query = "SELECT * FROM supplier WHERE deleted=1";

                Connection connection = Sql.getSqlConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(query);

                DefaultTableModel model = new DefaultTableModel(){
                                public boolean isCellEditable(int row, int column) {
                                    return false;
                                    }
                            };
                model.addColumn("Code");
                model.addColumn("Name");
                model.addColumn("Terms");
                model.addColumn("Beginning Balance");
                model.addColumn("Address");
                model.addColumn("Contact Person");
                model.addColumn("Telephone No.");
                model.addColumn("Fax No.");

                while(rs.next()) {
                   Vector rowData = new Vector () ;

                   rowData.add(rs.getString("suppCode"));
                   rowData.add(rs.getString("suppName"));
                   rowData.add(rs.getString("suppTerms"));
                   rowData.add(rs.getString("suppBegBal"));
                   rowData.add(rs.getString("suppAddr"));
                   rowData.add(rs.getString("suppConPerson"));
                   rowData.add(rs.getString("suppTelNo"));
                   rowData.add(rs.getString("suppFaxNo"));
                   model.addRow(rowData);
                }

                supplierTable.setModel(model);
                Sql.closeSqlConnection(connection);

            } catch (Exception ex) {
                Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        else if(key.equals("%"))
        {
            showTable();
        }

        else {

        try {
            String query = "SELECT * FROM Supplier WHERE (suppCode LIKE '"+key+"' or suppName LIKE '"+key+"' or suppTerms LIKE '"+key+"' or suppBegBal LIKE '"+key+"' or suppAddr LIKE '"+key+"' or suppConPerson LIKE '"+key+"' or suppTelNo LIKE '"+key+"' or suppFaxNo LIKE '"+key+"') AND deleted=0";
            
            Connection connection = Sql.getSqlConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);

            DefaultTableModel model = new DefaultTableModel(){
			    public boolean isCellEditable(int row, int column) {
			    	return false;
				}
			};
            model.addColumn("Code");
            model.addColumn("Name");
            model.addColumn("Terms");
            model.addColumn("Beginning Balance");
            model.addColumn("Address");
            model.addColumn("Contact Person");
            model.addColumn("Telephone No.");
            model.addColumn("Fax No.");

            while(rs.next()) {
               Vector rowData = new Vector () ;

               rowData.add(rs.getString("suppCode"));
               rowData.add(rs.getString("suppName"));
               rowData.add(rs.getString("suppTerms"));
               rowData.add(rs.getString("suppBegBal"));
               rowData.add(rs.getString("suppAddr"));
               rowData.add(rs.getString("suppConPerson"));
               rowData.add(rs.getString("suppTelNo"));
               rowData.add(rs.getString("suppFaxNo"));
               model.addRow(rowData);
            }

            supplierTable.setModel(model);
            Sql.closeSqlConnection(connection);

        } catch (Exception ex) {
            Logger.getLogger(Chassis.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

}
